package cn.wolfcode.mq.listener;

import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderPayTimeOutListener",
        topic = MQConstant.ORDER_PAY_TIMEOUT_TOPIC
)
public class OrderPayTimeOutListener implements RocketMQListener<OrderMQResult> {

    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        // 查询订单支付状态
        String orderNo = orderMQResult.getOrderNo();
        if (!StringUtils.isEmpty(orderNo)){
            OrderInfo orderInfo = orderInfoService.get(orderNo);
            if (orderInfo != null) {
                // 判断是否是未支付
                if (OrderInfo.STATUS_ARREARAGE.equals(orderInfo.getStatus())) {
                    Long seckillId = orderMQResult.getSeckillId();
                    // 回补真实库存
                    seckillProductService.incrStock(seckillId);
                    // 回补预库存
                    seckillProductService.rollbackRedisStock(orderMQResult.getTime(), seckillId);
                    // 修改订单标识
                    rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC, seckillId);
                    // 修改订单状态
                    orderInfoService.changeCancelStatus(orderNo, OrderInfo.STATUS_TIMEOUT);
                }
            }
        }
    }
}
